/**
 * Created by reeves on 2017/1/25.
 */
Template.postSubmit.onCreated(function () {
    Session.set('postSubmitErrors', {});
});

Template.postSubmit.helpers({
    errorMessage: function (field) {
        return Session.get('postSubmitErrors')[field];
    },
    errorClass: function (field) {
        return !!Session.get('postSubmitErrors')[field] ? 'has-error' : '';
    },
    category: function () {
        return Category.find();
    }
});

Template.postSubmit.events({
    'submit form': function (e) {
        e.preventDefault();

        var post = {
            url: $(e.target).find('[name=url]').val(),
            title: $(e.target).find('[name=title]').val(),
            category: $(e.target).find('[name=category]').val(), // 添加分类信息
            star: 0
        };

        var errors = validatePost(post);
        if (errors.title || errors.url)
            return Session.set('postSubmitErrors', errors);

        Meteor.call('postInsert', post, function (error, result) {
            // 向用户显示错误信息并终止
            if (error)
                return throwError(error.reason);

            // 显示结果，跳转页面
            if (result.postExists)
                throwError('This link has already been posted');

            Router.go('postPage', {_id: result._id});
        });
    },
    'keyup #url': function (e, template) {
        var url = $('#url').val();
        $('#title').val('正在尝试自动获取标题...');
        $('#title').attr('disabled', true);

        /* 需要加入url检验 */
        var httpIndex = url.indexOf("http://"),
            httpsIndex = url.indexOf("https://");

        if(httpIndex==0 || httpsIndex==0){
            Meteor.call('getUrlTitle', url, function (error, result) {
                $('#title').attr('disabled', false);

                if (error) {
                    console.log('error occurred');
                } else {
                    $('#title').val(result);
                }
            })
        }else {
            $('#title').val('网址格式有误...');
            $('#title').attr('disabled', false);
        }

    }
});